package com.webware.one.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.InvocationException;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.webware.one.client.ui.Dialog;
import com.webware.one.shared.dto.UserDto;
import com.webware.one.shared.exception.SessionExpireSecurityException;

public class Site implements EntryPoint {

    public static void handleError(Throwable caught) {
	if (caught instanceof InvocationException
		&& caught.getMessage()
			.contains("This session has been expired")) {
	    refresh();
	}
	if (caught instanceof SessionExpireSecurityException)
	    refresh();
	else
	    Dialog.alertHint(caught.getMessage());
    }

    public final static GwtRpcServiceAsync service = GWT
	    .create(GwtRpcService.class);
    public final static AppMessages messages = GWT.create(AppMessages.class);
    private Element loadingElement = DOM.getElementById("loading");

    public static UserDto user;

    @Override
    public void onModuleLoad() {
	// TODO проверку на полную загрузку gwt
	RootLayoutPanel.get().getElement().getStyle()
		.setOverflow(Overflow.HIDDEN);

	// Заполняем базу
	service.test(new SimpleAsyncCallback<Void>() {
	    public void onSuccess(Void result) {
		onModuleLoadImpl();
	    }
	});
    }

    private void onModuleLoadImpl() {
	// Достаём пользователя из сессии
	service.getCurrentUser(new SimpleAsyncCallback<UserDto>() {
	    public void onSuccess(UserDto user) {
		// Убираем вертелку от начальной загрузки
		// loadingElement.getStyle().setDisplay(Display.NONE);
		if (loadingElement != null
			&& loadingElement.getParentElement() != null)
		    loadingElement.removeFromParent();

		loginComplete(user);

	    }
	});
    }

    public static void loginComplete(UserDto user) {
	System.out.println("Site.loginComplete()");
	assert user != null;
	Site.user = user;

	RootLayoutPanel.get().clear();
	RootLayoutPanel.get().setStyleName("root");

	Label label = new Label();
	if (user.isAdminRole())
	    label.setText("Admin");
	else {
	    label.setText("User");
	}
	RootLayoutPanel.get().add(label);
    }

    public native static void refresh()/*-{
		$wnd.location.reload(true);
    }-*/;

    public native static void redirect(String url)/*-{
		$wnd.location.replace(url);
    }-*/;
}